﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Web;
using System.Web.Mvc;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.Mvc;
using Dogshow.Model;
using Dogshow.Web.Services;
using DogshowRepository;
using Ninject;

namespace Dogshow.Web.Controllers
{
    public class MestaController : Controller
    {
        private readonly IRepoServices m_Repository;

        public MestaController(IRepoServices mRepository)
        {
            m_Repository = mRepository;
        }

        public ActionResult Index()
        {
            var mesta = m_Repository.VratiMesta1();
            HttpContext.Application["Mesta"] = mesta;
            ViewBag.SifarnikMesta = mesta;
            return View(new Mesto());
        }

        public PartialViewResult VratiMesta()
        {
            var mesta = HttpContext.Application["Mesta"];
            ViewBag.SifarnikMesta = mesta; 
            return PartialView("MestaGridView", mesta);
        }

        [HttpPost]
        public ActionResult AzuirajMesto(Mesto mesto)
        {
            if (ModelState.IsValid)
            {
                m_Repository.SacuvajMesto(mesto);
                return RedirectToAction("Index");
            }
            var mesta = HttpContext.Application["Mesta"];
            ViewData["SifarnikMesta"] = mesta;
            return View("Index", mesto);
        }

        public PartialViewResult MestaComboPartial()
        {
            return PartialView("MestaCombo", null);
        }

        public static object FiltrirajMesta(ListEditItemsRequestedByFilterConditionEventArgs args)
        {
            var repository = ((IKernel) Bootstrap.Bootstrapper.Container).Get<IMestaRepository>();
            var mesta = repository.FiltrirajPoNazivu(args.Filter, args.BeginIndex, args.EndIndex - args.BeginIndex + 1);
            return mesta;
        }

        public static object FiltrirajMestoPoId(ListEditItemRequestedByValueEventArgs args)
        {
            if (args.Value == null) return null;
            var repository = ((IKernel)Bootstrap.Bootstrapper.Container).Get<IMestaRepository>();
            var id = Convert.ToInt32(args.Value);
            return repository.VratiPoId(id);
        }

        public static IEnumerable<Mesto> VratiMestoPoId(int? idMesta)
        {
            if (idMesta == null) return Enumerable.Empty<Mesto>();
             var repository = ((IKernel)Bootstrap.Bootstrapper.Container).Get<IMestaRepository>();
            return new []{repository.VratiPoId(idMesta.Value) ?? new Mesto()};
        }
    }
}
